// 鼠标按下函数
const fnDown = (el, ev) => {
  console.log(ev);
  // div的位置
  let currentX = el.offsetLeft;
  let currentY = el.offsetTop;
  console.log("元素位置:(" + currentX + "," + currentY + ")");
  // 鼠标按下位置
  let downX = ev.clientX;
  let downY = ev.clientY;
  console.log("鼠标位置:(" + downX + "," + downY + ")");

  // 鼠标移动监听函数
  const fnMove = ev => {
    console.log(ev);
    // 计算移动后的位置
    let left = ev.clientX - downX + currentX;
    let top = ev.clientY - downY + currentY;
    // 修改元素移动后的位置
    el.style.left = left + "px";
    el.style.top = top + "px";
  };
  // 按下之后监听文档的鼠标移动事件(拖动快可能拖出div)
  document.addEventListener("mousemove", fnMove, false);

  // 鼠标放开监听函数
  const fnUp = ev => {
    console.log(ev);
    document.removeEventListener("mousemove", fnMove, false);
    document.removeEventListener("mouseup", fnMove, false);
  };
  // 文档中鼠标放开事件
  document.addEventListener("mouseup", fnUp, false);
  return false;
};

// 导出函数
export default el => {
  // 传递元素进来即可
  // 函数中也用到el,所以使用bind绑定参数到函数即可
  // 函数bind的参数在前面，默认参数在其后
  el.addEventListener("mousedown", fnDown.bind(null, el), false);
};
